﻿///////////////////////////////////////////////////////////////////////////////
//	Copyright 2013 JASDev International
//
//	Licensed under the Apache License, Version 2.0 (the "License");
//	you may not use this file except in compliance with the License.
//	You may obtain a copy of the License at
//
//		http://www.apache.org/licenses/LICENSE-2.0
//
//	Unless required by applicable law or agreed to in writing, software
//	distributed under the License is distributed on an "AS IS" BASIS,
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//	See the License for the specific language governing permissions and
//	limitations under the License.
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Text;

using JDI.Common.Utils;

namespace JDI.Pusher.Client
{
	/// <summary>
	/// Represents a Pusher Private channel.
	/// </summary>
	public class PusherPrivateChannel : PusherChannel
	{
		internal PusherPrivateChannel(string channelName, PusherClient pusher) : base(channelName, pusher)
		{
			this.channelType = PusherChannelType.Private;
		}

		public virtual bool TriggerEvent(string eventName, string eventData = null)
		{
			// TODO - return error info to the user somehow??
			if (this.status != PusherChannelState.Subscribed)
				return false;

			if (eventName.ToLower().IndexOf("client-") != 0)
			{
		//		this.OnError("Client event names must begin with \"client-\".");
				return false;
			}

			return this.pusher.SendClientEvent(this.name, eventName, eventData);
		}

		internal override void Subscribe(PusherDelegates.ChannelStatusCallback callback = null)
		{
			this.statusCallback = callback;

			this.status = PusherChannelState.Authorizing;

			if (this.statusCallback != null)
			{
				this.statusCallback(this.status);
			}

			// TODO - do authorization then subscribe
			/*
			using (var webClient = new System.Net.WebClient())
			{
				string data = String.Format("channel_name={0}&socket_id={1}", channelName, this.socketID);

				webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
				webClient.UploadStringCompleted += webClient_UploadStringCompleted;
				webClient.UploadStringAsync(new Uri(ChannelAuthEndpoint), null, data, this.channels[channelName]);
			}
			*/
	
			
			this.pusher.SendSubscribeRequest(this.name);
		}

		// TODO - do we need this??
		protected bool CheckAuthEndpoint()
		{
			if (StringUtil.IsNullOrEmpty(this.pusher.AuthEndpoint))
			{
			//	this.OnError("AuthEndpoint must be set before calling Subscribe for a Private or Presence channel.");
				return false;
			}
			return true;
		}
	}
}
